package main

import (
	"context"
	"fmt"
	"log"
	apis "month_zh5/client/api"
	"month_zh5/common/nacos"
	"month_zh5/common/viper_config"
	"month_zh5/service/logger"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	logger.Logger()
	config := viper_config.ViperConfig("server", "./config", "Nacos")
	nacos.NewNaCos(config["ipaddr"], config["dataid"], config["group"])
	nac := nacos.NacosConfig
	router := gin.Default()
	apis.Register(router)

	srv := &http.Server{
		Addr:    fmt.Sprintf("%s:%v", nac.Gin.Host, nac.Gin.Port),
		Handler: router,
	}
	go func() {
		// 服务连接
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Println("Server exiting")
}
